import 'dart:math';
import 'math_utils.dart';

// 计算磁偏角的函数
double calculateMagneticDeclination(double longitude, double latitude) {
  // 地球的磁场模型参数（需要查找更准确的数据）
  const double magneticFieldStrength = 0.0512367; // 单位：nT (纳特斯拉)
  const double magneticFieldDeclinationRate = -2.5; // 单位：°/year (每年)
  const double magneticFieldVariation = 0.001; // 单位：nT (纳特斯拉)
  const double magneticFieldVariationRate = -0.002; // 单位：°/year (每年)

  // 经纬度的弧度值
  double longitudeRad = degreesToRadians(longitude);
  double latitudeRad = degreesToRadians(latitude);

  // 计算磁偏角（以弧度为单位）
  double magneticDeclinationRad =
      atan2(sin(longitudeRad) * magneticFieldVariation, magneticFieldStrength);
  double magneticVariationRad = magneticFieldVariationRate * cos(latitudeRad);
  magneticDeclinationRad += magneticVariationRad;
  magneticDeclinationRad += magneticFieldDeclinationRate *
      (longitudeRad - pi * (longitudeRad / (2 * pi)).floor());

  double magneticDeclinationDeg = radiansToDegrees(magneticDeclinationRad); // 将弧度转换为度数
  magneticDeclinationDeg =
      roundToNearest(magneticDeclinationRad, 30); // 取整到最近的30度
  return magneticDeclinationDeg;
}
